package de.hauck.rtmidlet.views;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import de.hauck.rtmidlet.DownloadImageThread;
import de.hauck.rtmidlet.RTMidlet;
import de.hauck.rtmidlet.model.Configuration;
import de.hauck.rtmidlet.model.StockBean;
import de.hauck.rtmidlet.model.StockStore;
import de.hauck.rtmidlet.utils.Utils;

public class CanvasCharts extends Canvas implements CommandListener {
	private Configuration c;
	private Display _display;
	private Displayable _dble;
	private Image conn_status, conn_red, conn_yellow, conn_green;
	private Font f;
	private Image[] imageArray;
	private Image[] imageArrayOverview;
	private String[] downloadTime;
	private Vector _stocksVec;

	private String params;
	private String chart;
	private boolean overview = true;

	private int slideNr = 1;
	private int maxSlides = 1;

	private int startNr = 0;
	private int stocksOnScreen = 6;
	private int endNr = startNr + stocksOnScreen;
	private int selectedChart = 0;
	private StockBean stock;
	private String stockName;
	private int _type;
	private String url = "";

	public CanvasCharts(int type, Display display, Displayable dble,
			Vector stocksVec, StockStore mystore) {
		_display = display;
		_dble = dble;
		_stocksVec = stocksVec;
		_type = type;
		// String url = "";

		// current = 0;
		imageArray = new Image[stocksVec.size()];
		imageArrayOverview = new Image[stocksVec.size()];
		downloadTime = new String[stocksVec.size()];
		maxSlides = (stocksVec.size() / stocksOnScreen);
		if ((stocksVec.size() % stocksOnScreen) > 0)
			maxSlides++;
		System.out.println("maxSlides: " + maxSlides);

		setFullScreenMode(true);
		setCommandListener(this);
		try {
			conn_red = Image.createImage("/conn_red.png");
			conn_yellow = Image.createImage("/conn_yellow.png");
			conn_green = Image.createImage("/conn_green.png");
			conn_status = conn_red;
		} catch (IOException e) {
			e.printStackTrace();
		}
		f = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN,
				Font.SIZE_SMALL);
	}

	protected void paint(Graphics g) {
		// clear screen
		g.setColor(0, 0, 0);
		g.fillRect(0, 0, getWidth(), getHeight());

		g.setFont(f);
		if (overview) {
			int x_cols = 0;
			int y_row = 10;
			startNr = slideNr * stocksOnScreen - stocksOnScreen;
			endNr = Math.min(startNr + stocksOnScreen, _stocksVec.size());
			for (int i = startNr; i < endNr; i++) {
				stock = (StockBean) _stocksVec.elementAt(i);
				stockName = stock.getName();
				if (stockName.length() > 10)
					stockName = stockName.substring(0, 9) + ".";

				// scale all available images
				if (imageArray[i] != null) {
					try {
						if (imageArrayOverview[i] == null)
							if (_type == c.FILTER_CHART_FT)
								imageArrayOverview[i] = Utils.rotateImage(
										Utils.rescaleImage(imageArray[i], 80, 100),
										270);
							else
								imageArrayOverview[i] = Utils.rescaleImage(
										imageArray[i], 100, 80);
						g.drawImage(imageArrayOverview[i], x_cols + 60, y_row,
								Graphics.TOP | Graphics.HCENTER);
						g.setColor(0, 0, 0);
						g.drawString("" + stockName, x_cols + 60, y_row,
								Graphics.TOP | Graphics.HCENTER);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					g.setColor(255, 255, 255);
					g.drawString("" + stockName, x_cols + 60, y_row,
							Graphics.TOP | Graphics.HCENTER);
					g.drawString("unavailable", x_cols + 60, y_row + 15,
							Graphics.TOP | Graphics.HCENTER);
				}
				if (selectedChart == i) {
					g.setColor(255, 0, 0);
					g.drawRoundRect(x_cols + 8, y_row - 2, 102, 82, 10, 10);
				}

				if (x_cols == 120)
					y_row += 90;
				x_cols = (x_cols + 120) % 240;
			}
			if (maxSlides > 1) {
				g.setColor(255, 255, 255);
				g.drawString(slideNr + "/" + maxSlides, getWidth(),
						getHeight(), Graphics.BOTTOM | Graphics.RIGHT);
			}

		} else {
			// draw chart & text

			if (imageArray[selectedChart] != null) {
				g.setColor(0, 0, 0);
				System.out.println("currentImage: " + selectedChart
						+ " != null");
				g.drawImage(imageArray[selectedChart], getWidth() / 2, getHeight()/2,
						Graphics.VCENTER | Graphics.HCENTER);
				// if image<screensize, set white color
				if (imageArray[selectedChart].getHeight()<getHeight())
					g.setColor(255,255,255);
				else g.setColor(0,0,0);
				g.drawString(downloadTime[selectedChart], getWidth(),
						getHeight(), Graphics.BOTTOM | Graphics.RIGHT);

			} else {
				g.setColor(255, 255, 255);
				g.drawString("No data available yet", getWidth() / 2,
						getHeight() / 2, Graphics.TOP | Graphics.HCENTER);
			}
			
			g
					.drawString(((StockBean) _stocksVec
							.elementAt(selectedChart)).getName(), 0,
							getHeight(), Graphics.BOTTOM | Graphics.LEFT);
			g.drawImage(conn_status, getWidth(), 0, Graphics.TOP
					| Graphics.RIGHT);
		}
	}

	public void commandAction(Command arg0, Displayable arg1) {

	}

	protected void keyPressed(int keyCode) {
		int action = getGameAction(keyCode);
		if (action == UP) {
			if (overview) {
				selectedChart -= 2;
				if (selectedChart < 0) {
					selectedChart += 2;
				}
				if (selectedChart < startNr && slideNr > 1) {
					slideNr--;
				}
				// System.out.println("SlideNr: " + slideNr + ", selected: "
				// + selectedChart);
			} else {
				// get previous chart
				selectedChart--;
				// System.out.println("current: " + selectedChart);
				if (selectedChart < 0)
					selectedChart = _stocksVec.size() - 1;
				if (imageArray[selectedChart] == null) 
				downloadImage();
			}
			this.repaint();
		} else if (action == DOWN) {
			if (overview) {
				System.out.println("startnr: " + startNr + " endnr: " + endNr
						+ ", size: " + _stocksVec.size());
				selectedChart += 2;
				// if (selected>endNr) selected-=1;
				if (selectedChart >= endNr && slideNr < maxSlides) {
					slideNr++;
				}
				if (selectedChart >= _stocksVec.size() - 1)
					selectedChart = _stocksVec.size() - 1;

				// System.out.println("SlideNr: " + slideNr + ", selected: "
				// + selectedChart);
			} else {
				// get next chart
				selectedChart++;
				// System.out.println("current: " + selectedChart);
				if (selectedChart >= _stocksVec.size())
					selectedChart = 0;
				if (imageArray[selectedChart] == null) downloadImage();
			}
			this.repaint();
		} else if (action == LEFT) {
			if (overview) {
				selectedChart--;
				if (selectedChart < startNr && slideNr > 1) {
					slideNr--;
				}
				if (selectedChart < 0) {
					selectedChart = _stocksVec.size() - 1;
					slideNr = maxSlides;
				}
				// System.out.println("SlideNr: " + slideNr + ", selected: "
				// + selectedChart);
				this.repaint();
			}
		} else if (action == RIGHT) {
			if (overview) {
				// System.out.println(startNr + " " + endNr);
				selectedChart++;

				if (selectedChart >= endNr && slideNr < maxSlides) {
					slideNr++;
				}
				if (selectedChart == _stocksVec.size()) {

					slideNr = 1;
					selectedChart = 0;
				}
				// System.out.println("SlideNr: " + slideNr + ", selected: "
				// + selectedChart);

				this.repaint();
			}
		} else if (action == FIRE) {
			overview = !overview;
			if (!overview && imageArray[selectedChart] == null) {
				downloadImage();
			}
			this.repaint();
		} else if (keyCode == KEY_NUM1) {
			// 1 = update data
			
			downloadImage();
			
			this.repaint();
		} else if (keyCode == -6 || keyCode == -7) {
			// exit
			_display.setCurrent(_dble);
		} else if (keyCode == Canvas.KEY_POUND) {
			// # = toggles to overview-screen
			overview = !overview;
			this.repaint();
		} else if (keyCode == KEY_NUM3) {
			// scroll page up
			if (overview) {
				// selected = 0;
				// get previous slide
				if (slideNr > 1) {
					slideNr--;
					selectedChart -= stocksOnScreen;
				}
			}
			System.out.println("SlideNr: " + slideNr + ", selected: "
					+ selectedChart);
			this.repaint();
		} else if (keyCode == KEY_NUM9) {
			// 9 = scroll page down
			// selected = 0;
			// get next slide
			if (slideNr < maxSlides) {
				slideNr++;
				selectedChart += stocksOnScreen;
				if (selectedChart >= _stocksVec.size() - 1)
					selectedChart = _stocksVec.size() - 1;
			}

			System.out.println("SlideNr: " + slideNr + ", selected: "
					+ selectedChart);
			this.repaint();
		} else {
			System.out.println("key: " + keyCode);
			this.repaint();
		}
	}

	public void updateStatus(int i) {
		switch (i) {
		case 0: {
			conn_status = conn_red;
			repaint();
			break;
		}
		case 1: {
			conn_status = conn_yellow;
			repaint();
			break;
		}
		case 2: {
			conn_status = conn_green;
			repaint();
			break;
		}
		}
	}

	public void showPic(Image image, int i) {
		try {
			if (_type == c.FILTER_CHART_FT)
				imageArray[i] = Utils.rotateImage(image, 90);
			else
				imageArray[i] = image;
			Calendar cal = Calendar.getInstance();
			cal.setTime(new Date(System.currentTimeMillis()));
			downloadTime[i] = Utils.convertCal2Time(cal, true);
			repaint();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	

	private void downloadImage() {
			params = "&height=" + getWidth() + "&width=" + getHeight();
			String chartName = "";
			if (_type == c.FILTER_CHART_FT) {
				chartName = ((StockBean) _stocksVec.elementAt(selectedChart))
						.getSymbolFt();
//				if (chartName.indexOf(".") == -1)
//					chart = "&instrumentId=" + chartName;
//				else
//					chart = "&instrumentKey=" + chartName;
				url = c.getURL(c.FINANZTREFF, chartName) + params;
			} else if (_type == c.FILTER_CHART_RT) {
				chartName = ((StockBean) _stocksVec.elementAt(selectedChart))
						.getSymbolRT();
				url = c.getURL(c.RT, chartName);
			}
			if (chartName!=null && !chartName.equals(""))
			new DownloadImageThread(url, selectedChart, this);
			else {
				RTMidlet.getInstance().setCurrent(this);
				overview=true;
				RTMidlet.getInstance().alert("Info", "No symbol maintained.", Configuration.ALERT_WAIT_TIME);
			}
			System.out.println(url);
	}
}
